package com.kpi.processflow.process;

import com.kpi.processflow.node.Node;
import com.kpi.processflow.process.factory.ProcessFactory;
import com.kpi.processflow.record.Context;
import com.kpi.processflow.record.Profiler;
import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.MessageFormat;
import java.util.List;

/**
 * @author Kevin Liu
 * @date 2020/5/3 6:52 下午
 */
@Slf4j
@Component
@Primary
public class ProcessTrigger {

    @Autowired
    private ProcessFactory processRegistry;

    public ProcessTrigger() {
    }

    public void fire(Context context) {
        List<Node> nodes = this.processRegistry.getProcessNodes(context.getBizCode(), context.getOperation());
        if (CollectionUtils.isEmpty(nodes)) {
            log.error("find nodes is null, bizCode = {}, operation = {}, context = {}", context.getBizCode(), context.getBizCode(), context);
            throw new RuntimeException(MessageFormat.format("The trade node with bizCode [{0}] and operation [{1}] not exists.", context.getBizCode(), context.getBizCode()));
        } else {
            nodes.forEach((node) -> {
                Profiler.record(node.getNodeCode());
                node.execute(context);
                Profiler.release();
            });
        }
    }

}
